package com.ifonly.datatables;

import com.ifonly.activerecord.DbUtils;
import com.ifonly.activerecord.Record;
import com.ifonly.activerecord.common.Pagination;
import com.ifonly.datatables.sql.DTSelectSql;
import com.ifonly.datatables.sql.DTSql;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * <p>
 * . DataTables 响应参数的封装
 * </p>
 *
 * @author Jerry Ou
 * @version 1.0 2015-08-31 13:43
 * @since JDK 1.6
 */
public class DTResponse<E> {
    /**
     * 表示 DataTables 请求次数，返回给 DataTables
     */
    private int draw;
    /**
     * 总记录数
     */
    private long recordsTotal;
    /**
     * 查询过滤之后的总记录数
     */
    private long recordsFiltered;
    /**
     * 页面数据
     */
    private List<E> data;


    /**
     * 构造方法
     *
     * @param draw DataTables 请求次数
     * @param recordsTotal 总记录数
     * @param recordsFiltered 查询过滤之后的总记录数
     * @param data 页面数据
     */
    private DTResponse(int draw, long recordsTotal, long recordsFiltered, List<E> data) {
        this.draw = draw;
        this.recordsTotal = recordsTotal;
        this.recordsFiltered = recordsFiltered;
        this.data = data;
    }

    public static DTResponse<Record> newInstance(DTRequest dtRequest, String segment, String keyword) {
        DTSql dtSql = new DTSelectSql(dtRequest);
        dtSql.init(segment, keyword);
        int draw = dtRequest.getDraw();
        Pagination<Record> pagination = DbUtils.pagination(dtSql.getSql(), dtRequest.getStart(), dtRequest.getLength(), dtSql.getParams().toArray());
        return new DTResponse<Record>(draw, pagination.getTotalRecords(), pagination.getTotalRecords(), pagination.getRecords());
    }

    public static DTResponse<Record> newInstance(HttpServletRequest request, String segment, String keyword) {
        DTRequest dtRequest = DTRequest.newInstance(request);
        return newInstance(dtRequest, segment, keyword);
    }

    /**
     * 构建DTResponse对象
     *
     * @param draw DataTables 请求次数
     * @param recordsTotal 总记录数
     * @param recordsFiltered 查询过滤之后的总记录数
     * @param data 页面数据
     * @param <E> 页面数据范型
     * @return DTResponse对象
     */
    public static <E> DTResponse<E> newInstance(int draw, long recordsTotal, long recordsFiltered, List<E> data) {
        return new DTResponse<E>(draw, recordsTotal, recordsFiltered, data);
    }

    public int getDraw() {
        return draw;
    }

    public long getRecordsTotal() {
        return recordsTotal;
    }

    public long getRecordsFiltered() {
        return recordsFiltered;
    }

    public List<E> getData() {
        return data;
    }


    @Override
    public String toString() {
        return "DTResponse{" +
                "draw=" + draw +
                ", recordsTotal=" + recordsTotal +
                ", recordsFiltered=" + recordsFiltered +
                ", data=" + data +
                '}';
    }
}
